package com.maning.imagebrowserlibrary;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.maning.imagebrowserlibrary.model.ImageDetailBean;
import com.maning.imagebrowserlibrary.view.SmoothImageView;

public class LargeImageBrowserActivity extends Activity {

    //图片详情
    public static final String IMAGE_DETAIL = "imageDetail";

    //图片url
    private String mRes;
    //图片相对于屏幕的X位置
    private int mLocationX = 0;
    //图片相对于屏幕的Y的位置
    private int mLocationY = 0;
    //图片的宽
    private int mWidth = 0;
    //图片的宽
    private int mHeight = 0;
    //图片放大缩小
    private SmoothImageView imageView;
    //图片信息
    private ImageDetailBean imageDetailBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Intent intent = getIntent();
        imageDetailBean = intent.getParcelableExtra(IMAGE_DETAIL);
        mRes = imageDetailBean.getImages();
        mLocationX = imageDetailBean.getLocationX();
        mLocationY = imageDetailBean.getLocationY();
        mWidth = imageDetailBean.getSelfWidth();
        mHeight = imageDetailBean.getSelfHeight();
        imageView = new SmoothImageView(this);
        setContentView(initImageView(imageView));
        loadSkillIDetailImage();
    }

    private void loadSkillIDetailImage() {
        if (imageView != null && imageDetailBean != null) {
            Glide.with(this)
                    .load(mRes)
                    .into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }

    private SmoothImageView initImageView(SmoothImageView imageView) {
        imageView.setOriginalInfo(mWidth, mHeight, mLocationX, mLocationY);
        imageView.transformIn();
        imageView.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);//不要轻易用fitXY，容易OOM
        return imageView;
    }

    @Override
    public void onBackPressed() {
        if (imageView == null) {
            super.onBackPressed();
        } else {
            imageView.transformOut();
            imageView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    LargeImageBrowserActivity.super.onBackPressed();
                }
            }, 300);
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_skill_image_detail_enter, R.anim.anim_skill_image_detail_exit);
    }
}
